package com.example.safeassistan.home.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.PermissionChecker;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseActivity;
import com.example.safeassistan.common.UserData;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.home.adapter.BackLogFragmentAdapter;
import com.example.safeassistan.home.adapter.HiddenDangerInvestigationParentAdapter;
import com.example.safeassistan.home.adapter.InvestigationTabAdapter;
import com.example.safeassistan.home.fragment.InvestagionFragment;
import com.example.safeassistan.home.listener.OnGroupExpandedListener;
import com.example.safeassistan.home.model.BackLogFragmentModel;
import com.example.safeassistan.home.model.InvestigationFinishMOdel;
import com.example.safeassistan.home.model.InvestigationModel;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.main.MainActivity;
import com.example.safeassistan.utile.JsonUtils;
import com.example.safeassistan.utile.ToastUtil;
import com.example.safeassistan.widget.CustomExpandableListView;
import com.example.safeassistan.widget.HiddendangerInvestigationDialog;
import com.example.safeassistan.widget.WarningDialog;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.google.gson.internal.$Gson$Preconditions;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.example.safeassistan.constants.Constants.PAGESIZE;

public class HiddenDangerinvestigation extends BaseActivity implements View.OnClickListener {
    private static final int REQUEST_CODE = 101;
    private TextView _barTvRight;
    private ViewPager viewPager;
    private RecyclerView rcTab;
    private InvestigationTabAdapter tabAdapter;
    private TextView tvControl;//分级管控
    private TextView tvRiskName,tvRiskName1;
    private String defId="";
    private String riskPointName="";

    private Integer isControl=0;//0 分级管控 1 其他
    private String riskPointId="";
    private String checkTableId="";//检查表id

    private List<BackLogFragmentModel.ResultDTO.RecordsDTO.DangerVOListDTO> model;
    private List<Fragment> fragmentList;
    private MainAdapter mainAdapter;
    private String address="";

    private int posi=0;//1 返回到待办任务下一级  0 返回到首页

    public static void actionStart(int posi,Context context, String defId, String riskPointName, Integer isControl, String riskPointId,
                                   String checkTableId,List<BackLogFragmentModel.ResultDTO.RecordsDTO.DangerVOListDTO > modellist) {
        Intent intent = new Intent(context, HiddenDangerinvestigation.class);
        intent.putExtra("posi",posi);
        intent.putExtra("defId",defId);
        intent.putExtra("isControl",isControl);
        intent.putExtra("riskPointName",riskPointName);
        intent.putExtra("riskPointId",riskPointId);
        intent.putExtra("checkTableId",checkTableId);
        intent.putExtra("model",(Serializable) modellist);
        context.startActivity(intent);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id._barTvRight:
                //完成
                WarningDialog dialog=new WarningDialog(getContext(),
                        "是否确定已完成所有检查？","取消","确定","");
                dialog.setClicklistener(new WarningDialog.ClickListenerInterface() {
                    @Override
                    public void doCancel() {
                        dialog.dismiss();
                    }

                    @Override
                    public void doConfirm() {
                        submitFinishData();
                        dialog.dismiss();
                    }
                });
                dialog.show();
                break;
        }
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.hiddendanger_investigation;
    }

    @Override
    protected void initView() {
        setTitleText("隐患排查");
        posi=getIntent().getIntExtra("posi",0);
        defId=getIntent().getStringExtra("defId");//任务检查记录表
        riskPointName=getIntent().getStringExtra("riskPointName");
        isControl=getIntent().getIntExtra("isControl",0);
        riskPointId=getIntent().getStringExtra("riskPointId");
        checkTableId=getIntent().getStringExtra("checkTableId");//检查表id
        model=(List<BackLogFragmentModel.ResultDTO.RecordsDTO.DangerVOListDTO>)getIntent().getSerializableExtra("model");

        _barTvRight=findViewById(R.id._barTvRight);
        tvRiskName1=findViewById(R.id.tvRiskName1);
        rcTab=findViewById(R.id.rcTab);
        viewPager=findViewById(R.id.viewPager);
        _barTvRight.setText("完成");
        tvRiskName=findViewById(R.id.tvRiskName);
        _barTvRight.setVisibility(View.VISIBLE);
        tvControl=findViewById(R.id.tvControl);
        _barTvRight.setOnClickListener(this::onClick);
        _barTvRight.setTextColor(getResources().getColor(R.color.blue_3B5BEA));

        tvRiskName.setText("风险点名称："+(riskPointName==null?"":riskPointName));
        tvRiskName1.setText("风险点名称："+(riskPointName==null?"":riskPointName));
        if (isControl==0){
            tvControl.setVisibility(View.VISIBLE);
            tvRiskName1.setVisibility(View.VISIBLE);
        }else {
            tvControl.setVisibility(View.GONE);
            tvRiskName1.setVisibility(View.GONE);
        }

        if (model!=null&&model.size()>0){
            fragmentList=new ArrayList<>();

            for (int i=0;i<model.size();i++){
                fragmentList.add(InvestagionFragment.newInstance(model.get(i).getId(),riskPointId,defId,checkTableId));
            }
            if (model.size()==1&&model.get(0).getDangerSrcName().equals("")){
                rcTab.setVisibility(View.GONE);
            }else {
                rcTab.setVisibility(View.VISIBLE);
            }

            mainAdapter=new MainAdapter(getSupportFragmentManager());
            viewPager.setAdapter(mainAdapter);
            tabAdapter=new InvestigationTabAdapter(model);
            rcTab.setAdapter(tabAdapter);
            rcTab.setLayoutManager(new LinearLayoutManager(this,RecyclerView.HORIZONTAL,false));
            tabAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    for (int i=0;i<model.size();i++){
                        model.get(i).setSelect(false);
                    }
                    model.get(position).setSelect(true);
                    tabAdapter.notifyDataSetChanged();
                    viewPager.setCurrentItem(position);
                }
            });

            viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    for (int i=0;i<model.size();i++){
                        model.get(i).setSelect(false);
                    }
                    model.get(position).setSelect(true);
                    tabAdapter.notifyDataSetChanged();
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
        }
        checkPermission();
    }

    public void submitFinishData(){
        JSONObject map=new JSONObject();
        try {
            map.put("checkTableId",checkTableId);//检查表id
            map.put("riskPointId",riskPointId);//风险点id
            if(!defId.equals("")){
                map.put("defRecordId",defId);//检查记录表id
            }
            map.put("checkAddress",address);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(this).doPost(UrlConstants.checkrecordFinish, null, map, new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {

                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean  success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), InvestigationFinishMOdel.class);
                        if (obj instanceof InvestigationFinishMOdel) {
                            InvestigationFinishMOdel  investigationFinishMOdel=(InvestigationFinishMOdel) obj;
                            _barTvRight.setVisibility(View.GONE);
                            if (investigationFinishMOdel.getResult().getUserList()!=null&&investigationFinishMOdel.getResult().getUserList().size()>0){
                                WarningDialog finishDialog=new WarningDialog(getContext(),"检查已完成，是否要评价现场人员？",
                                        "取消","确定","");
                                finishDialog.setClicklistener(new WarningDialog.ClickListenerInterface() {
                                    @Override
                                    public void doCancel() {
                                        finishDialog.dismiss();
                                        if (posi==1){
                                            //返回到任务
                                            ActivityBacksecond.actionStart(getContext(), defId, checkTableId);
                                            finish();
                                        }else if(posi==2){
                                            ActivityBacklogList.actionStart(HiddenDangerinvestigation.this);
                                            finish();
                                        }else {
                                            MainActivity.actionStart(HiddenDangerinvestigation.this,0);
                                            finish();
                                        }
                                    }

                                    @Override
                                    public void doConfirm() {
                                        finishDialog.dismiss();
                                        PersonCommentAddList.actionStart(getContext(),investigationFinishMOdel,riskPointId);
                                        finish();
                                    }
                                });
                                finishDialog.show();
                            }else {
                                if (posi==1){
                                    //返回到任务
                                    ActivityBacksecond.actionStart(getContext(), defId, checkTableId);
                                    finish();
                                }else if(posi==2){
                                    ActivityBacklogList.actionStart(HiddenDangerinvestigation.this);
                                    finish();
                                }else {
                                    MainActivity.actionStart(HiddenDangerinvestigation.this,0);
                                    finish();
                                }
                            }
                        }
                    }else {
                        Toast.makeText(HiddenDangerinvestigation.this,message,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int status, String msg) {

            }
        });
    }

                @Override
    protected void initData() { }

    @Override
    protected int getTitleBarType() {
        return 0;
    }



    //适配器
    public class MainAdapter extends FragmentPagerAdapter {

        public MainAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        //获取标题
        @Override
        public CharSequence getPageTitle(int position) {
            return model.get(position).getDangerSrcName();
        }
    }

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //可在其中解析amapLocation获取相应内容。
                    address=amapLocation.getAddress();
                    Log.e("address",address);
                }else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError","location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    public void initLocation(){

//初始化定位
        mLocationClient = new AMapLocationClient(HiddenDangerinvestigation.this);
//设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
//初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(20000);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
//启动定位
        mLocationClient.startLocation();
    }


    @SuppressLint("MissingSuperCall")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.d("aaa", "onRequestPermissionsResult: " +
                            "权限申请成功");
                    for (int i : grantResults) {
                        Log.d("aaa", "onRequestPermissionsResult: " + i);
                    }
                    initLocation();
                } else {
                    Toast.makeText(HiddenDangerinvestigation.this, "您已拒绝申请权限", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    /****权限**/
    private void checkPermission(){
        try{
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (PermissionChecker.checkSelfPermission(HiddenDangerinvestigation.this, Manifest.permission.ACCESS_COARSE_LOCATION)!= PermissionChecker.PERMISSION_GRANTED||
                PermissionChecker.checkSelfPermission(HiddenDangerinvestigation.this,Manifest.permission.ACCESS_BACKGROUND_LOCATION)!=PermissionChecker.PERMISSION_GRANTED) {
                    // 不相等 请求授权
                    ActivityCompat.requestPermissions(
                            HiddenDangerinvestigation.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                                    Manifest.permission.ACCESS_BACKGROUND_LOCATION
                    },REQUEST_CODE);
                }else {
                    initLocation();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    // 获取数据
    public void getData(){
        JSONObject map = new JSONObject();
        try {
            map.put("defId",defId);
            map.put("pageNo", String.valueOf(1));
            map.put("pageSize",String.valueOf(PAGESIZE));
            map.put("status",String.valueOf(1));
            if (!riskPointName.equals("")){
                map.put("riskName",riskPointName);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(HiddenDangerinvestigation.this).doPost(UrlConstants.agendaTaskDetails, null, map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), BackLogFragmentModel.class);
                        if (obj instanceof BackLogFragmentModel) {
                            BackLogFragmentModel model=(BackLogFragmentModel) obj;
                                if (model.getResult().getRecords().size() > 0) {

                                }
                        }
                    }else {
                        Toast.makeText(HiddenDangerinvestigation.this,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }
}